package com.navi168.fwq21.util;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.za.communication.core.codec.decoder.DataSegmentationDecoder;
import org.za.communication.core.codec.encoder.DataCombineEncoder;
import org.za.communication.core.handler.SessionIdleHandler;
import org.za.communication.core.util.ZipUtil;
import org.za.communication.message.GetVerifyCodeMessage;
import org.za.communication.message.Loginmessage;
import org.za.communication.message.RegisterMessage;

import com.navi168.fwq21.R;
import com.navi168.fwq21.db.Sqlh;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class Login extends Activity {
	private EditText username;
	private EditText password;
	private Button reg;
	private Button login;
	private Button findpassword;
	private CheckBox remBox;
	private int isrem = 0;
	private ProgressDialog progDialog;
	private SessionIdleHandler sessionIdleHandler = new SessionIdleHandler();
	private String TAG = "mylog";
	private boolean remember;
	private String md5;
	private	String friendlistmd5 ;
	private String carlistmd5 ;
	private Sqlh sqlh;

	private HashMap<String, String> friendnumber = new HashMap<String, String>();
	private Context mContext = null;
	private static final String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER };
	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;

	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		 

		mContext = this.getApplicationContext();
		sqlh = sqlh.getInstance(mContext);
		SharedPreferences preferences = mContext.getSharedPreferences(
				Constants.SPF, Context.MODE_WORLD_READABLE);

		boolean islogin = preferences.getBoolean("islogin", false);
		friendlistmd5 = preferences.getString("friendlistmd5", "");
		carlistmd5 = preferences.getString("carlistmd5", "");
		
		findviews();
		setlisters();
		getSIMContacts();
		getPhoneContacts();
		
		
		
		try {

			md5 = new MD5Util().md5Hex(new ZipUtil().zip(getTxl(friendnumber)
					.getBytes("utf-8")));

//			md5f = new MD5Util().md5Hex(new ZipUtil().zip(sqlh.getAllMob().getBytes("utf-8")));
//			md5c = new MD5Util().md5Hex(new ZipUtil().zip(sqlh.getAllCar().getBytes("utf-8")));
			

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (islogin) {
			Intent intent = new Intent(Login.this, MainPage.class);
			intent.putExtra("md5", md5);
			intent.putExtra("md5f", friendlistmd5);
			intent.putExtra("md5c", carlistmd5);
			intent.putExtra("txlc", getTxl(friendnumber));
			startActivity(intent);
		}
		

	}

	private void setlisters() {
		reg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Login.this, Register.class);

				startActivity(intent);

				Login.this.finish();

			}
		});

		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toLogin();

			}
		});

		findpassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

		remBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				if (isChecked) {
					remember = true;
					// editor.putBoolean("islogin", true);
				} else {
					remember = false;
					// editor.putBoolean("islogin", false);

				}

			}
		});

	}

	private void findviews() {
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		reg = (Button) findViewById(R.id.regbutton);
		login = (Button) findViewById(R.id.loginbutton);
		findpassword = (Button) findViewById(R.id.findpassword);
		remBox = (CheckBox) findViewById(R.id.cokeing);
		progDialog = new ProgressDialog(this);
	}

	private void toLogin() {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				socketServer();
			}
		});
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("登录信息提交中...");
		progDialog.show();
		thread.start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constants.LOGIN_OK) {
				progDialog.dismiss();
				showToast("登录成功！");
				Intent intent = new Intent(Login.this, MainPage.class);
				intent.putExtra("md5", md5);
				intent.putExtra("md5f", friendlistmd5);
				intent.putExtra("md5c", carlistmd5);
				intent.putExtra("txlc", getTxl(friendnumber));

				if (remember) {
					SharedPreferences settings = mContext.getSharedPreferences(
							Constants.SPF, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putBoolean("islogin", true);
					editor.putString("mymobile", username.getText().toString().trim());
					editor.commit();
				}
				startActivity(intent);
				Login.this.finish();

			}
			if (msg.what == Constants.LOGIN_NO) {
				progDialog.dismiss();
				showToast("用户没有注册！");
			}
			if (msg.what == Constants.LOGIN_PASS) {
				progDialog.dismiss();
				showToast("密码错误！");
			}
			if (msg.what == Constants.LOGIN_OTHER) {
				progDialog.dismiss();
				showToast("无法登录，请稍后再试...！");
			}

		}
	};

	private void socketServer() {
		byte[] head = new byte[2];
		head[0] = (byte) 0xff;
		head[1] = (byte) 0xff;

		List<Integer> l = new ArrayList<Integer>();// 需要加密
		l.add(0x01);
		l.add(0x02);
		l.add(0x03);
		l.add(0x05);
		l.add(0x06);
		List<Integer> l2 = new ArrayList<Integer>();// 需要解密
		l2.add(0x04);
		l2.add(0x52);
		l2.add(0x53);
		l2.add(0x54);

		DataCombineEncoder encoder = new DataCombineEncoder();
		encoder.setHead(head);
		encoder.setEncryptIdList(l);

		DataSegmentationDecoder decoder = new DataSegmentationDecoder();
		decoder.setHead(head);
		decoder.setDecryptIdList(l2);

		IoConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(30000);

		connector.getFilterChain().addLast("mycodec",
				new ProtocolCodecFilter(encoder, decoder));
		connector.setHandler(sessionIdleHandler);
		ConnectFuture future = connector.connect(new InetSocketAddress(
				"tsp.navi168.com", 9123));
		future.awaitUninterruptibly();
		IoSession session = future.getSession();
		// 获取密钥
		GetVerifyCodeMessage message = new GetVerifyCodeMessage();

		Loginmessage lmessage = new Loginmessage();

		try {
			session.write(message);// 发送获取密钥信息
			byte[] key = new byte[4];
			// 通过sessionidlehandler 获取全局变量
			boolean gogo = true;

			while (gogo) {
				if (sessionIdleHandler.go) {
					Log.i(TAG, "可以获取key了");
					key = sessionIdleHandler.key;
					gogo = false;
					sessionIdleHandler.go = false;
				}

			}
			lmessage.setKey(key);
			lmessage.setMobile(username.getText().toString());
			lmessage.setPassword(password.getText().toString());
			session.write(lmessage);
			while (true) {

				if (sessionIdleHandler.flag != "") {
					String flag = sessionIdleHandler.flag;
					Log.i(TAG, "SessionIdleHandler.flag-"
							+ sessionIdleHandler.flag + "-");
					if (flag == "ok" || flag.equals("ok")) {
						handler.sendMessage(Message.obtain(handler,
								Constants.LOGIN_OK));

					} else if (flag == "no" || flag.equals("no")) {

						handler.sendMessage(Message.obtain(handler,
								Constants.LOGIN_NO));
					} else if (flag == "pass" || flag.equals("pass")) {
						handler.sendMessage(Message.obtain(handler,
								Constants.LOGIN_PASS));
					} else if (flag == "other" || flag.equals("other")) {
						handler.sendMessage(Message.obtain(handler,
								Constants.LOGIN_OTHER));
					}
					sessionIdleHandler.flag = "";
					break;
				}

			}

		} catch (Exception ee) {
			System.out.println(ee);
		}

	}

	private void showToast(String showString) {
		Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT)
				.show();
	}

	private void getPhoneContacts() {
		ContentResolver resolver = mContext.getContentResolver();

		// 获取手机联系人
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {

				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				// 当手机号码为空的或者为空字段 跳过当前循环
				if (phoneNumber.length() != 11)
					continue;

				// 得到联系人名称
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);
				Log.i(TAG, contactName + "contactName");

				friendnumber.put(phoneNumber, contactName);

			}

			phoneCursor.close();
		}
	}

	private void getSIMContacts() {
		ContentResolver resolver = mContext.getContentResolver();
		// 获取Sims卡联系人
		Uri uri = Uri.parse("content://icc/adn");
		Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
				null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {

				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				// 当手机号码为空的或者为空字段 跳过当前循环
				if (phoneNumber.length() != 11)
					continue;
				// 得到联系人名称
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);
				Log.i(TAG, contactName + "contactName");

				friendnumber.put(phoneNumber, contactName);
			}

			phoneCursor.close();
		}
	}

	private String getTxl(HashMap<String, String> txls) {
		String returString = "";
		Iterator iter = txls.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			String val = (String) entry.getValue();
			returString += val + "|" + key + "||";

		}
		returString = returString.substring(0, returString.length() - 2);
		Log.i(TAG, returString);

		return returString;

	}
	

}
